package com.baitai.framework.web.service;

import com.baitai.common.exception.base.BaseException;
import com.baitai.common.exception.user.UserException;
import com.baitai.common.utils.SMSUtil;
import com.baitai.system.domain.SysUserRole;
import com.baitai.system.mapper.SysUserRoleMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import com.baitai.common.constant.CacheConstants;
import com.baitai.common.constant.Constants;
import com.baitai.common.constant.UserConstants;
import com.baitai.common.core.domain.entity.SysUser;
import com.baitai.common.core.domain.model.RegisterBody;
import com.baitai.common.core.redis.RedisCache;
import com.baitai.common.exception.user.CaptchaException;
import com.baitai.common.exception.user.CaptchaExpireException;
import com.baitai.common.utils.MessageUtils;
import com.baitai.common.utils.SecurityUtils;
import com.baitai.common.utils.StringUtils;
import com.baitai.framework.manager.AsyncManager;
import com.baitai.framework.manager.factory.AsyncFactory;
import com.baitai.system.service.ISysConfigService;
import com.baitai.system.service.ISysUserService;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.concurrent.TimeUnit;

/**
 * 注册校验方法
 * 
 * @author ruoyi
 */
@Component
public class SysRegisterService
{
    @Autowired
    private ISysUserService userService;
    @Autowired
    private RedisCache redisCache;
    @Autowired
    private SysUserRoleMapper userRoleMapper;

    @Value("${aliyun.sms.access-id}")
    private String smsId;

    @Value("${aliyun.sms.access-key}")
    private String smsSecret;

    @Value("${aliyun.sms.endpoint}")
    private String endpoint;

    @Value("${aliyun.sms.signName}")
    private String signName;

    @Value("${aliyun.sms.templateCode}")
    private String templateCode;

    /**
     * 注册
     */
    @Transactional
    public String register(RegisterBody registerBody)
    {
        String msg = "", username = registerBody.getUsername(), password = registerBody.getPassword();
        SysUser sysUser = new SysUser();
        sysUser.setUserName(username);
        validatePhoneCaptcha(registerBody.getUsername(),registerBody.getCode());
        // 验证码开关 todo短信验证
//        boolean captchaEnabled = configService.selectCaptchaEnabled();
//        if (captchaEnabled)
//        {
//            validateCaptcha(username, registerBody.getCode(), registerBody.getUuid());
//        }

        if (StringUtils.isEmpty(username))
        {
            msg = "用户名不能为空";
        }
        else if (StringUtils.isEmpty(password))
        {
            msg = "用户密码不能为空";
        }
        else if (username.length() < UserConstants.USERNAME_MIN_LENGTH
                || username.length() > UserConstants.USERNAME_MAX_LENGTH)
        {
            msg = "账户长度必须在2到20个字符之间";
        }
        else if (password.length() < UserConstants.PASSWORD_MIN_LENGTH
                || password.length() > UserConstants.PASSWORD_MAX_LENGTH)
        {
            msg = "密码长度必须在5到20个字符之间";
        }
        else if (!userService.checkUserNameUnique(sysUser))
        {
            msg = "保存用户'" + username + "'失败，注册账号已存在";
        }
        else
        {

            sysUser.setNickName(username);
            sysUser.setPhonenumber(username);
            sysUser.setUserPoints("0");
            sysUser.setTotalPoints("0");
            sysUser.setAvatar("/profile/avatar/logo.png");
            sysUser.setPassword(SecurityUtils.encryptPassword(password));
            if(StringUtils.isNotEmpty(registerBody.getInvitationCode())){
                String invitationCode = registerBody.getInvitationCode().replaceAll("HPYOUTAO","");
                sysUser.setParentId(invitationCode);
                SysUser user = userService.selectUserById(Long.parseLong(invitationCode));
                if(StringUtils.isNotEmpty(user.getAncestor())){
                    sysUser.setAncestor(user.getAncestor()+","+invitationCode);
                }else {
                    sysUser.setAncestor(invitationCode);
                }
            }
            boolean regFlag = userService.registerUser(sysUser);
            Long[] a =  {101l};
            insertUserRole(sysUser.getUserId(),a);
            if (!regFlag)
            {
                msg = "注册失败,请联系系统管理人员";
            }
            else
            {
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.REGISTER, MessageUtils.message("user.register.success"),""));
            }
        }
        return msg;
    }
    /**
     * 新增用户角色信息
     *
     * @param userId 用户ID
     * @param roleIds 角色组
     */
    public void insertUserRole(Long userId, Long[] roleIds)
    {
        if (StringUtils.isNotEmpty(roleIds))
        {
            // 新增用户与角色管理
            List<SysUserRole> list = new ArrayList<SysUserRole>(roleIds.length);
            for (Long roleId : roleIds)
            {
                SysUserRole ur = new SysUserRole();
                ur.setUserId(userId);
                ur.setRoleId(roleId);
                list.add(ur);
            }
            userRoleMapper.batchUserRole(list);
        }
    }
    /**
     * 校验验证码
     * 
     * @param username 用户名
     * @param code 验证码
     * @param uuid 唯一标识
     * @return 结果
     */
    public void validateCaptcha(String username, String code, String uuid)
    {
        String verifyKey = CacheConstants.CAPTCHA_CODE_KEY + StringUtils.nvl(uuid, "");
        String captcha = redisCache.getCacheObject(verifyKey);
        redisCache.deleteObject(verifyKey);
        if (captcha == null)
        {
            throw new CaptchaExpireException();
        }
        if (!code.equalsIgnoreCase(captcha))
        {
            throw new CaptchaException();
        }
    }

    /**
     * 校验验证码
     *
     * @param username 用户名
     * @param code 验证码
     * @return 结果
     */
    public void validatePhoneCaptcha(String username, String code)
    {
        String verifyKey = CacheConstants.REGISTER_KEY+username;
        String captcha = redisCache.getCacheObject(verifyKey);
        if (StringUtils.isEmpty(code))
        {
            throw new BaseException("register","请输入验证码");
        }
        if (captcha == null)
        {
            throw new BaseException("register","验证码错误或已过期请重新发送");
        }
        if (!code.equalsIgnoreCase(captcha))
        {
            throw new BaseException("register","验证码错误请重新输入");
        }
        redisCache.deleteObject(verifyKey);
    }

    public String sendSmsVerificationCode(String phoneNumber,String isRegister) throws Exception{
        if(StringUtils.isEmpty(phoneNumber)){
            return  "请输入手机号";
        }
        if(StringUtils.isNotEmpty(isRegister)&&"1".equals(isRegister)){
            SysUser sysUser = new SysUser();
            sysUser.setUserName(phoneNumber);
            if (!userService.checkUserNameUnique(sysUser))
            {
                return "注册账号已存在";
            }
        }
        //发送验证码
        String code = generateFourDigitCode();
        String verifyKey = CacheConstants.REGISTER_KEY+phoneNumber;
        redisCache.setCacheObject(verifyKey,code,300, TimeUnit.SECONDS);
        System.out.println("verifyKey=====>"+code);
        SMSUtil.sendSms(phoneNumber,code,endpoint,smsId,smsSecret,signName,templateCode);
        return "发送成功";
    }
    public static String generateFourDigitCode() {
        Random random = new Random();
        // 初始化一个StringBuilder来构建最终的验证码字符串
        StringBuilder sb = new StringBuilder();

        // 循环四次，每次生成一个0-9之间的随机数并添加到StringBuilder中
        for (int i = 0; i < 4; i++) {
            int digit = random.nextInt(10); // 生成0-9之间的随机数
            sb.append(digit); // 将随机数添加到StringBuilder中
        }

        // 将StringBuilder转换为String并返回
        return sb.toString();
    }

    public String getAppUrl(String invitationCode) {
        invitationCode = invitationCode.replaceAll("HPYOUTAO","");
        SysUser user = userService.selectUserById(Long.parseLong(invitationCode));
        String url = "";
        if(StringUtils.isNotEmpty(user.getAncestor())){
            String[] userId = user.getAncestor().split(",");
            if(userId.length>0){
                if ("1".equals(userId[0])&&userId.length==1){
                    url = user.getAppUrl();
                }else if ("1".equals(userId[0])&&userId.length>1){
                    user = userService.selectUserById(Long.parseLong(userId[1]));
                    url = user.getAppUrl();
                }else {
                    user = userService.selectUserById(Long.parseLong(userId[0]));
                    url = user.getAppUrl();
                }
            }
        }
        return url;
    }

    public String getPhoneUrl(String phone) {
        SysUser user = userService.selectUserByUserPhone(phone);
        String url = "";
        if(StringUtils.isNotEmpty(user.getAncestor())){
            String[] userId = user.getAncestor().split(",");
            if(userId.length>0){
                if ("1".equals(userId[0])&&userId.length==1){
                    url = user.getAppUrl();
                }else if ("1".equals(userId[0])&&userId.length>1){
                    user = userService.selectUserById(Long.parseLong(userId[1]));
                    url = user.getAppUrl();
                }else {
                    user = userService.selectUserById(Long.parseLong(userId[0]));
                    url = user.getAppUrl();
                }
            }
        }
        return url;
    }
}
